package cn.rongdao.jrkabao.ui.information;


import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.mifengkong.frtools.http.request.callback.FRBaseObserver;
import com.mifengkong.frtools.ui.activity.FRStartActivity;
import com.mifengkong.frtools.ui.statusbar.FRStatusBar;
import com.mifengkong.frtools.util.FRDisplayMetrics;
import com.mifengkong.frwidget.dialog.FRDialog;
import com.mifengkong.frwidget.dialog.FRDialogClickListener;
import com.mifengkong.frwidget.titlebar.TitleBarUIComponent;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import cn.rongdao.jrkabao.R;
import cn.rongdao.jrkabao.base.FRBaseLooperRequestActivity;
import cn.rongdao.jrkabao.bean.information.QuotaBean;
import cn.rongdao.jrkabao.bean.information.apply.ApplyInfoBean;
import cn.rongdao.jrkabao.constant.InfoConstant;
import cn.rongdao.jrkabao.model.information.QuotaDataModel;
import cn.rongdao.jrkabao.ui.IdentificationVerificate.IdentificationWithValidationItem.IdentificationWithCreditCardActivity;
import cn.rongdao.jrkabao.ui.information.adapter.MyQuotaAdapter;
import cn.rongdao.jrkabao.ui.information.event.QuotaChangeEvent;
import cn.rongdao.jrkabao.ui.loan.LoanListActivity;
import cn.rongdao.jrkabao.util.NumberUtil;
import cn.rongdao.jrkabao.widget.CustomCircleView;


/*
* Created by Wang on 17/9/20.
* 我的额度界面
* */
public class MyQuotaActivity extends FRBaseLooperRequestActivity {

    @BindView(R.id.amq_title_bar)
    TitleBarUIComponent titleBarUIComponent;
    @BindView(R.id.my_quota_progressView)
    CustomCircleView circleView;
    @BindView(R.id.amq_recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.amq_myquota_up)
    ImageView mAmqMyquotaUp;
    private MyQuotaAdapter myQuotaAdapter;
    private int screenHeightSize;
    private int itemStatus;
    private String mOlderQuota;
    private boolean creditCradDataImportReturn = false;
    private FRDialog alertDialog;


    public static void start(Context context) {
        FRStartActivity.start(context, MyQuotaActivity.class);
    }

    @Override
    protected int layoutRes() {
        return R.layout.activity_my_quota;
    }

    @Override
    protected void initView() {
        super.initView();
        FRStatusBar.setTranslucentForImageView(this, findViewById(R.id.amq_rootview));
        screenHeightSize = getResources().getDisplayMetrics().heightPixels;
        circleView.setNeedSmallCircle(false);
        circleView.setCenterTextMarginTop(FRDisplayMetrics.dp2px(this, 5));
        initTitle();
        initRecyclerView();
        initListener();
        initMiLiDaiDialog();
    }


    /*获取网络数据*/
    private void getData() {
        //1 通过 -1 正在验证 2 实名不匹配  0  没用填过资料
        QuotaDataModel.getInstance().execute("0", new FRBaseObserver<QuotaBean>(this, TextUtils.isEmpty(mOlderQuota) ? "正在加载" : null) {
            @Override
            protected void onBaseNext(QuotaBean data) {
                if (data != null) {
                    int validation_num = data.getUnder_verification_num();
                    if (validation_num == 0) {
                        stopRunning();
                    } else {
                        startRun();
                    }
                    initData(data);
                }
            }

        });
    }

    /*设置数据*/
    private void initData(QuotaBean data) {
        //给半圆进度设置值
        initCircleView(data.getValidation_num() * 20, NumberUtil.splitNum(data.getQuota()));
        List<QuotaBean.ValidationBean> validation = data.getValidation();
        initLoanListIcon(validation);
        myQuotaAdapter.setRefreshData(validation);
        searchData(validation);
    }

    /*初始化贷款列表的Icon*/
    private void initLoanListIcon(List<QuotaBean.ValidationBean> validation) {
        for (int i = 0; i < validation.size(); i++) {
            QuotaBean.ValidationBean validationBean = validation.get(i);
            String material_code = validationBean.getMaterial_code();
            if (InfoConstant.IDENTITY_INFO.equals(material_code)) {
                int verify_status = validationBean.getVerify_status();
                if (1 == verify_status) {
                    mAmqMyquotaUp.setVisibility(View.VISIBLE);
                } else {
                    mAmqMyquotaUp.setVisibility(View.GONE);
                }
            }
        }
    }

    private void searchData(List<QuotaBean.ValidationBean> validation) {
        for (int i = 0; i < validation.size(); i++) {
            QuotaBean.ValidationBean validationBean = validation.get(i);
            String material_code = validationBean.getMaterial_code();
            if (InfoConstant.IDENTITY_INFO.equals(material_code)) {
                itemStatus = validationBean.getVerify_status();
            } else if (InfoConstant.CREDIT_VERIFY.equals(material_code)) {
                if (validationBean.getVerify_status() == 0 && creditCradDataImportReturn) {
                    alertDialog.show();
                    creditCradDataImportReturn = false;
                }
            }
        }
    }

    @Override
    protected ApplyInfoBean.FirstItemBean getUserFirstFillInItem() {
        return new ApplyInfoBean.FirstItemBean(InfoConstant.IDENTITY_INFO, itemStatus);
    }

    /*初始化列表数值*/
    private void initRecyclerView() {
        int recHeight = (int) (screenHeightSize * 0.66);
        RelativeLayout.LayoutParams lps = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, recHeight);
        lps.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        lps.addRule(RelativeLayout.BELOW, R.id.amq_headerview);
        recyclerView.setLayoutParams(lps);
        myQuotaAdapter = new MyQuotaAdapter(0);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        //recyclerView.addItemDecoration(new GridDivider(this, 1, getResources().getColor(R.color.line_color_bg)));
        recyclerView.setAdapter(myQuotaAdapter);
    }

    /*初始化半圆的初始值*/
    private void initCircleView(int angle, String quota) {
        if (!quota.equals(mOlderQuota)) {
            circleView.setCurrentAngle(angle);
            circleView.setCenterTextNumber(quota, 28);
            circleView.setDefaultArcWidth(FRDisplayMetrics.dp2px(this, 3));
            mOlderQuota = quota;
            EventBus.getDefault().post(new QuotaChangeEvent());
        }

    }

    /*初始化TitleBar的数据*/
    private void initTitle() {
        //返回键
        titleBarUIComponent.initLeftBack(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //标题
        titleBarUIComponent.initTitle("我的额度");
        //右边客服
        titleBarUIComponent.initRightTvServiceWhite(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startHelpCenter();
            }
        });

    }

    /*设置控件的点击事件*/
    private void initListener() {
        myQuotaAdapter.setOnItemActionListener(listener);
        mAmqMyquotaUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LoanListActivity.start(MyQuotaActivity.this);
            }
        });
    }

    @Override
    protected void baseLooperMethod() {
        super.baseLooperMethod();
        getData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!mIsRunning) {
            getData();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) { //resultCode为回传的标记，我在B中回传的是RESULT_OK
            case IdentificationWithCreditCardActivity.SUCCESS_RETURN_DATA_IMPORT:
                creditCradDataImportReturn = true;
                break;
        }
    }

    //    /*米拉贷弹窗*/
    private void initMiLiDaiDialog() {
        if (alertDialog == null) {
            alertDialog = new FRDialog.CommonBuilder(this)
                    .setContentView(R.layout.dialog_not_find_mail)
                    .setOnClickListener(R.id.dialog_miladai_sure, new FRDialogClickListener() {
                        @Override
                        public boolean onDialogClick(View view) {
                            toCreditCardActivity();
                            return true;
                        }
                    }).setOnClickListener(R.id.dialog_miladai_cancel, new FRDialogClickListener() {
                        @Override
                        public boolean onDialogClick(View view) {
                            return true;
                        }
                    })
                    .setFullWidth()
                    .setWidthOffset(0.77)
                    .setHeight(FRDisplayMetrics.dp2px(this, 173))
                    .setCancelableOutside(false)
                    .create();
        }
    }
}